<template>
  <div class="dingtalk-callback-container">
    <div class="loading-box">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <p>正在处理钉钉登录...</p>
    </div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { authAPI } from '@/api/index'

const route = useRoute()
const router = useRouter()

// 处理钉钉登录回调
const handleDingTalkCallback = async (code, types) => {
  try {
    const response = await authAPI.dingTalkCallback({ code, types })

    if (response.success) {
      // 登录成功，保存token和用户信息到localStorage
      localStorage.setItem('token', response.data.token)
      localStorage.setItem('retoken', response.data.retoken)
      localStorage.setItem('userInfo', JSON.stringify({
        user_id: response.data.user_id,
        phone: response.data.phone,
        username: response.data.username
      }))

      ElMessage.success('钉钉登录成功')
      
      // 跳转到首页
      router.push('/')
    } else if (response.code === 'USER_NOT_BOUND') {
      // 用户未绑定，跳转到手机号绑定页面
      // 保存钉钉用户信息，用于后续绑定
      localStorage.setItem('dingtalk_user_info', JSON.stringify(response.data.user_info))

      ElMessage.info('请绑定手机号完成注册')
      
      // 跳转到手机号绑定页面
      router.push('/bind-phone')
    } else {
      ElMessage.error(response.message || '钉钉登录失败')
      router.push('/login')
    }
  } catch (error) {
    console.error('钉钉登录失败:', error)
    ElMessage.error('钉钉登录失败，请重试')
    router.push('/login')
  }
}

// 在手机号绑定页面处理绑定
const handleBindPhone = async (phone, smsCode) => {
  try {
    const userInfo = localStorage.getItem('dingtalk_user_info')
    if (!userInfo) {
      ElMessage.error('钉钉登录信息已失效，请重新登录')
      router.push('/login')
      return
    }

    const response = await authAPI.bindPhone({
      user_info: JSON.parse(userInfo),
      phone,
      sms_code: smsCode
    })

    if (response.success) {
      // 绑定成功，保存token和用户信息到localStorage
      localStorage.setItem('token', response.data.token)
      localStorage.setItem('retoken', response.data.retoken)
      localStorage.setItem('userInfo', JSON.stringify({
        user_id: response.data.user_id,
        phone: response.data.phone,
        username: response.data.username
      }))

      // 清除临时存储的钉钉信息
      localStorage.removeItem('dingtalk_user_info')

      ElMessage.success('手机号绑定成功')
      
      // 跳转到首页
      router.push('/')
    } else {
      ElMessage.error(response.message || '绑定失败')
    }
  } catch (error) {
    console.error('绑定异常:', error)
    ElMessage.error('绑定失败，请重试')
  }
}

// 组件挂载时处理钉钉回调
onMounted(() => {
  const code = route.query.code
  const types = route.query.types
  
  if (code) {
    handleDingTalkCallback(code, types)
  } else {
    ElMessage.error('授权失败，请重新登录')
    router.push('/login')
  }
})

// 导出绑定方法供其他组件使用
defineExpose({
  handleBindPhone
})
</script>

<style scoped>
.dingtalk-callback-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1890ff 0%, #722ed1 100%);
}

.loading-box {
  text-align: center;
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.loading-icon {
  font-size: 48px;
  color: #1890ff;
  animation: rotate 2s linear infinite;
}

.loading-box p {
  margin-top: 20px;
  color: #666;
  font-size: 16px;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
